const {
    wxpusher,
    tiUserName,
    tiPassWord,
} = require('./ti_config');

const {
    logger,
    sleep,
    initPage,
    closeBrowser,
    randBetween,
    httpPost,
    httpGet,
    lpop,
} = require('./util');

const step1 = async page => {
    await mouseMoveAndClick(page, '.addressType');
    //等待按钮变红
    for (let i=0; i<5; i++) {
        const check = await page.$('.ti-button-disabled');
        if (check) {
            await sleep(2000);
        }
    }
    //内容已填好，直接下一步
    logger('下一步1');
    await mouseMoveAndClick(page, '#paid-shipping-address-select');
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/multi/cn-tax-invoice', { waitUntil: 'domcontentloaded' });
    //有时有可能会跳过发票确认，直接进入第3步的“规定”
    logger('等待页面跳转...');
    await page.waitForSelector('#cmpCheckboxflag', {
        timeout: 60000
    });
    await sleep(10000);
}

const step2 = async page => {
    logger('进入了发票确认页');
    await sleep(5000);
    //增值税发票确认
    logger('增值税发票确认');
    await mouseMoveAndClick(page, '#cmpCheckboxflag');
    await sleep(1000);
    //下一步
    logger('下一步2');
    await mouseMoveAndClick(page, '#tax-invoice-submit');
    await sleep(1000);
    //弹出弹框要求确认发票
    logger('确认发票并继续');
    const btn = await page.evaluate(async () => {
        return document.querySelectorAll('.vat-modal-button')[1];
    });
    await mouseMoveAndClickBy(page, btn);
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/choose', { waitUntil: 'domcontentloaded' });
    logger('等待页面跳转...');
    await page.waitForSelector('#regulations-select', {
        timeout: 60000
    });
    await sleep(10000);
}

const step3 = async page => {
    //规定 选择[游戏] 和 [游戏控制器和外设]
    logger('选择“游戏”和“游戏控制器和外设”，是否军方采购');
    await sleep(1000);
    try {
        await mouseMoveAndClick(page, '#waiver_accept');
    } catch(e) {}
    await page.evaluate(async () => {
        $('#regulations-select').val('游戏').change();
        await new Promise(resolve => setTimeout(resolve, 2000));
        $('#checkout-regulations-select').val('游戏控制器和外设').change();
    });
    await sleep(2000);
    const btn = await page.evaluate(async () => {
        return document.querySelectorAll('.militoryRadio')[1];
    });
    await mouseMoveAndClickBy(page, btn);
    await sleep(2000);
    await mouseMoveAndClickBy(page, btn);
    
    logger('等待按钮可点');
    //等待按钮变红
    for (let i=0; i<5; i++) {
        const check = await page.$('.ti-button-disabled');
        if (check) {
            await sleep(3000);
        }
    }
    //下一步
    logger('下一步3');
    await mouseMoveAndClick(page, '#regulations-submit-btn');
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-method/choose', { waitUntil: 'domcontentloaded' });
    logger('等待页面跳转...');
    await page.waitForSelector('.js-checkout-toc-radio', {
        timeout: 60000
    });
    await sleep(5000);
}

const step5 = async page => {
    //接受/拒绝
    //这里貌似需要滚一下里面的条款，才能点。所以直接用它自带的jQuery来修改
    logger('接受/拒绝');
    await sleep(5000);
    await page.evaluate(async () => {
        $('.js-checkout-toc-radio').prop("disabled", false);
        $('.toc-lbl-disabled').each(function() {
            $(this).removeClass('toc-lbl-disabled');
        });
    });
    await sleep(1000);
    await mouseMoveAndClick(page, '#terms_accept');
    await sleep(1000);
    await mouseMoveAndClick(page, '#terms_accept');
    await sleep(1000);

    //下一步
    logger('下一步4');
    await mouseMoveAndClick(page, '#shipping-method-submit');
    logger('等待页面跳转...');
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/payment-method/add', { waitUntil: 'domcontentloaded' });
    await page.waitForSelector('#payment-method-unionpay_b', {
        timeout: 60000
    });
    await sleep(10000);
}

const step6 = async page => {
    //支付方式，选择“企业支付”
    logger('选择支付方式');
    await sleep(5000);
    await mouseMoveAndClick(page, '#payment-method-unionpay_b');
    await page.waitForSelector('#warning-unionpay_b .js-apm-paymentbtn', {
        timeout: 60000
    });
    await sleep(2000);
    //确认
    logger('确认支付');
    await mouseMoveAndClick(page, '#warning-unionpay_b .js-apm-paymentbtn');
    logger('等待下单结果...');
    await page.waitForSelector('#citconPaymentDiv .modal-body iframe', {
        timeout: 60000
    });
    await sleep(10000);
}

//下单操作
const goAndPay = async (page, serial) => {
    try {
        logger('准备下单');

        await page.goto('https://www.ti.com.cn/store/ti/zh/cart');
        await page.waitForSelector('th.order_total', {
            timeout: 30000
        });

        //检查支付货币是否CNY
        const txt = await page.evaluate(() => document.querySelector('th.order_total').innerText);
        if (txt.indexOf('CNY') < 0) {
            logger('点击货币');
            const dropdown = await page.evaluateHandle(() => {
                return document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel").shadowRoot.querySelector(".ti-dropdown-panel-trigger");
            });
            await mouseMoveAndClickBy(page, dropdown);
            await sleep(1000);

            logger('选择CNY');
            const cny = await page.evaluateHandle(() => {
                return document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel li[data-value=\"CNY\"] a");
            });
            await mouseMoveAndClickBy(page, cny);
            await sleep(1000);

            logger('等待页面跳转');
            await page.waitForFunction(() => {
                return document.querySelector('th.order_total') && document.querySelector('th.order_total').innerText.indexOf('CNY') > -1;
            }, {
                timeout: 20000
            });
        }

        //跳转
        await page.goto('https://www.ti.com.cn/store/ti/zh/cart/checkout');
        await page.waitForSelector('.addressType', {
            timeout: 60000
        });

        await step1(page);
        await step2(page);
        await step3(page);
        await step5(page);
        await step6(page);

        logger('下单成功!');
    } catch(e) {
        logger('下单出错', e);
        return false;
    }

    logger('获取订单号');
    let orderNo = '';
    try {
        //获取订单号
        const iframe = await page.$('#citconPaymentDiv .modal-body iframe');
        const iframeUrl = await page.evaluate(dom => dom.getAttribute('src'), iframe);
        await page.goto(iframeUrl);
        logger(`打开订单页 ${iframeUrl}`);
        await page.waitForSelector('span.reference', {
            timeout: 60000
        });
        await sleep(10000);
        orderNo = await page.evaluate(() => {
            return document.querySelector('span.reference') && document.querySelector('span.reference').innerText;
        });
    } catch(e) {
        logger('获取订单号出错', page.url(), e);
    }

    const msg = '已成功下单，规格为：' + serial + '。本次订单号为：' + orderNo;
    logger(msg);

    //推送消息
    await httpPost('http://wxpusher.zjiecode.com/api/send/message', JSON.stringify({
        appToken: wxpusher.appToken,
        content: msg,
        contentType: 1,
        uids: wxpusher.uids,
    }), 'application/json');

    return true;
}

//鼠标移动并点击指定对象
const mouseMoveAndClickBy = async (page, dom) => {
    const box = await dom.boundingBox();
    const x = box.x + (box.width/2) - 3;
    const y = box.y + (box.height/2) - 2;
    await page.mouse.move(x, y, {steps:80});
    await page.mouse.click(x, y, {delay:100});
}

//鼠标移动并点击指定选择器
const mouseMoveAndClick = async (page, selector) => {
    const targetInput = await page.$(selector);
    const box = await targetInput.boundingBox();
    const x = box.x + (box.width/2) - 3;
    const y = box.y + (box.height/2) - 2;
    await page.mouse.move(x, y, {steps:80});
    await page.mouse.click(x, y, {delay:100});
}

//鼠标移动并输入
const mouseMoveAndInput = async (page, selector, txt) => {
    await mouseMoveAndClick(page, selector);
    await page.keyboard.type(txt, {delay:80});
}

const randomMoveAndClick = async page => {
    //鼠标随机移动4-6个地方
    const mouseMoveNum = randBetween(4, 6);
    logger('鼠标随机移动', mouseMoveNum, '次');
    for (let i=0; i<mouseMoveNum; i++) {
        const x = 10 + randBetween(100, 1700);
        const y = 110 + randBetween(200, 800);
        const steps = randBetween(30, 60);
        await page.mouse.move(x, y, {steps});
        await sleep(randBetween(200, 700));
    }

    logger('鼠标移动到输入框并点击');
    const targetInput = await page.$('ti-input');
    const box = await targetInput.boundingBox();
    const x1 = box.x + (box.width/2) - 3;
    const y1 = box.y + (box.height/2) - 2;
    const steps1 = randBetween(30, 60);
    await page.mouse.move(x1, y1, {steps:steps1});
    await page.mouse.click(x1, y1, {delay:200});
    await sleep(1000);
    logger('鼠标移出输入框并点击');
    const x2 = x1 - randBetween(100, 200);
    const y2 = y1 - randBetween(10, 200);
    const steps2 = randBetween(30, 60);
    await page.mouse.move(x2, y2, {steps:steps2});
    await page.mouse.click(x2, y2, {delay:100});
    await sleep(2000);
}

const webLogin = async page => {
    try {
        logger('开始登录');

        await page.goto('https://www.ti.com.cn/secure-link-forward/?gotoUrl=https%3A%2F%2Fwww.ti.com.cn%2F');
        await page.waitForSelector('input.u-width-full', {timeout: 60000});

        logger('输入帐号');
        await mouseMoveAndInput(page, 'input.u-width-full', tiUserName);
        await mouseMoveAndClick(page, '#nextbutton');
        await page.waitForTimeout(1000);

        //输入密码
        logger('输入密码');
        await mouseMoveAndInput(page, 'input[name=password]', tiPassWord);
        await mouseMoveAndClick(page, '#loginbutton');

        logger('等待登录结果');
        await page.waitForSelector('#homepage-carousel', {
            timeout: 60000,
        });
        logger('登录成功');
    } catch(e) {
        logger('登录失败', e);
        return false;
    }
    return true;
}

(async () => {

    const quickAddCartUrl = 'https://www.ti.com.cn/zh-cn/ordering-resources/buying-tools/quick-add-to-cart.html';

    while (1) {
        //检测任务
        const serial = await lpop('ti_worker_found');
        //const serial = 'INA849DR';
        if (!serial) {
            await sleep(1000);
            continue;
        }

        //获取最新库存
        const stockUrl = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn='+encodeURIComponent(serial);
        const res = JSON.parse(await httpGet(stockUrl, quickAddCartUrl));
        const stock = res.inventory;
        if (stock <= 0) {
            logger('已无库存，无法加购物车');
            continue;
        }

        //启动浏览器
        const page = await initPage();
        logger('启动浏览器');

        //登录
        if (!await webLogin(page)) {
            logger('登录失败');
            await closeBrowser();
            continue;
        }
        await page.goto(quickAddCartUrl);
        await randomMoveAndClick(page);

        const addNum = Math.min(stock, 10000);

        //成功{"cartId":"5a68dfda-f1a5-48e7-9a1d-dfeee765de02","statusType":"SUCCESS","statusCode":"200","message":"4 - Items added to the cart","cartResponsetList":null}
        const ret = await page.evaluate(async (addNum, serial) => {
            const ajax = () => {
                return new Promise(resolve => {
                    const timer = setTimeout(() => {
                        resolve('timeout');
                    }, 20000);
                    const xhr = new XMLHttpRequest();
                    xhr.open('post', 'https://www.ti.com.cn/occservices/v2/ti/addtocart', true);
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.onreadystatechange = function(){
                        if (xhr.readyState == 4) {
                            if (xhr.status == 200) {
                                resolve(xhr.responseText);
                            } else {
                                resolve(xhr.statusText);
                            }
                            clearTimeout(timer);
                        }
                    };
                    xhr.send(JSON.stringify({
                        cartRequestList:[{
                            opnId: serial,
                            packageOption: null,
                            quantity: addNum,
                            tiAddtoCartSource: 'ti.com-quickcart',
                        }],
                        currency:'CNY',
                    }));
                });
            }
            const ret = await ajax();
            return ret;
        }, addNum, serial);
        logger('加购物车结果', ret);
        if (ret[0] == '{') {
            const retJson = JSON.parse(ret);
            if (retJson.statusCode == 200) {
                logger('加购物车成功');
                //todo:发送通知
                await goAndPay(page, serial);
            } else {
                logger('加购物车不成功');
            }
        } else {
            //加购物车失败
            logger('加购物车失败');
        }
        await sleep(1800000);
    }

})();

